package com.cgsd.heyu.ui.info;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.android.library.utils.AppManager;
import com.android.library.utils.SharedPreferencesHelper;
import com.android.library.utils.StringUtils;
import com.android.library.utils.SystemUtil;
import com.android.library.utils.ToastHelper;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.cgsd.heyu.R;
import com.cgsd.heyu.address.ProvinceCityAreaBean;
import com.cgsd.heyu.address.SelectCityManager;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.AppMobclickAgent;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.entity.FlowerInfoEntity;
import com.cgsd.heyu.entity.StreetEntity;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.presenter.user.UserContract;
import com.cgsd.heyu.presenter.user.UserPresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.common.TabActivity;
import com.cgsd.heyu.ui.home.MainActivity;
import com.cgsd.heyu.ui.home.fragment.CenterFragment;
import com.cgsd.heyu.ui.login.AvatarSelectActivity;
import com.cgsd.heyu.ui.login.LoginActivity;
import com.cgsd.heyu.ui.webview.CommonH5Activity;
import com.cgsd.heyu.utils.LocationUtils;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.cgsd.heyu.widgets.dialog.AgreementDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoxing
 * Description 注册页面
 * CreateData: 2020/11/2
 */
public class AuthActivity extends BaseActivity<UserContract.Presenter> implements View.OnClickListener, TextWatcher, UserContract.AuthView {
    /**
     * 倒计时（60s）
     */
    private final long MILLISINFUTURE = 60 * 1000;
    /**
     * //步长（1s）
     */
    private final long COUNTDOWNINTERVAL = 1000;
    private CountDownTimer timer;
    private TextView edtPhone;
    private EditText edtCode;
    private TextView btnGetInto;
    private TextView tvSendCode;
    private String phone;
    private String code;
    private String realname;
    private String idcard;
    private String province;
    private String city;
    private String area;

    private String address;
    private TextView edtAddress;
    private TextView edtStreet;
    private EditText edtIdcard;
    private EditText edtRealname;
    private FlowerInfoEntity flowerInfoEntity;

    private SelectCityManager selectCityManager = null;
    int opPro;
    int opCity;
    int opArea;
    String street;
    private static Context mContext;
    private static List<String> streetList;
    private List<StreetEntity> streets;

    private OptionsPickerView optionsPickerView;



    public static void actionStart(Activity activity){
        /**
         * 到达此页面可清空用户相关数据和关闭所有页面
         */
        Intent intent = new Intent(activity, AuthActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_auth;
    }

    @Override
    protected void initView() {
        new UserPresenter(this);
        edtPhone = findViewById(R.id.edt_phone);
        edtRealname = findViewById(R.id.edt_realname);
        edtIdcard = findViewById(R.id.edt_idcard);
        edtCode = findViewById(R.id.edt_v_code);
        btnGetInto = findViewById(R.id.tv_get_into);
        tvSendCode = findViewById(R.id.tv_send_code);
        edtAddress = findViewById(R.id.edt_address);
        edtStreet = findViewById(R.id.edt_street);

        btnGetInto.setOnClickListener(this);
        tvSendCode.setOnClickListener(this);
        edtAddress.setOnClickListener(this);
        edtStreet.setOnClickListener(this);
        edtCode.addTextChangedListener(this);
        edtRealname.addTextChangedListener(this);
        edtIdcard.addTextChangedListener(this);
    }

    @Override
    protected void initData() {
        mPresenter.getFlowerInfo(UserModeConfig.getInstance().userId);
        edtPhone.setText(UserModeConfig.getInstance().mobileNo);

        timer = new CountDownTimer(MILLISINFUTURE, COUNTDOWNINTERVAL) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvSendCode.setEnabled(false);
                tvSendCode.setTextColor(Color.parseColor("#9A9A9A"));
                tvSendCode.setText("剩余"+millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                tvSendCode.setEnabled(true);
                tvSendCode.setTextColor(ContextCompat.getColor(AuthActivity.this,R.color.app_color));
                tvSendCode.setText(getString(R.string.send_v_code));
            }
        };

        if (!SystemUtil.isLocServiceEnable(this) || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                ||ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //添加还未授予的权限
            address="";
        }else {
            new LocationUtils(locationListener);
        }

    }

    /**
     * 当前未知返回监听
     */
    private LocationUtils.LocationListener locationListener = new LocationUtils.LocationListener() {

        @Override
        public void address(String localAddress) {
            address = localAddress;
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_get_into:
                if (StringUtils.isNotEmpty(province)){
                    if (StringUtils.isNotEmpty(street)){
                        showCommonSubmitDialog("");
                        mPresenter.auth(code, realname, idcard, street);
                    }else{
                        showToast("请选择所在县区");
                    }

                }else {
                    showToast("请选择所在地区");
                }

                break;
            case R.id.tv_send_code:
                String phone = edtPhone.getText().toString();
                showCommonSubmitDialog("");
                mPresenter.getVerificationCode(phone,"4");
                break;
            case R.id.edt_address:
                hideInput();
                initPicker();
                break;
            case R.id.edt_street:
                hideInput();
                optionsPickerView.show();
                break;

            default:
        }
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    private void initPicker() {
        if (selectCityManager == null) {
            selectCityManager = SelectCityManager.getInstance(this, true);
            selectCityManager.setOnSelectOptionListener((options1, provinceName, options2, cityName, options3, areaName) -> {
                opPro = options1;
                opCity = options2;
                opArea = options3;
                // 省           市             区
                String detail = provinceName + " " + cityName + " " + areaName;
                province = provinceName;
                city = cityName;
                area = areaName;
                edtAddress.setText(detail);
                mPresenter.streetList(province, city, area);
                //street

            });
        }
        selectCityManager.showDialog(opPro, opCity, opArea);
    }

    /**
     * 刷新登录进入按钮样式
     */
    private void refreshBtn() {
        realname = edtRealname.getText().toString();
        idcard = edtIdcard.getText().toString();
        code = edtCode.getText().toString();

        //if (code.length() >= 6 && idcard.length() >= 15 && StringUtils.isNotEmpty(realname)) {
        if (StringUtils.isNotEmpty(realname)) {
            btnGetInto.setEnabled(true);
        } else {
            btnGetInto.setEnabled(false);
        }
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullBar(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        refreshBtn();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void codeSuccess() {
        dismissCommonSubmitDialog();
        ToastHelper.showDefaultToast("发送成功");
        timer.start();
    }

    @Override
    public void streetList(List<StreetEntity> entity) {

        streets = entity;
        streetList = new ArrayList<>();
        edtStreet.setText(entity.get(0).name);
        street = entity.get(0).id;
        for (int i = 0; i < entity.size(); i++) {
            String streetName = entity.get(i).name;
            Log.v("streetList", streetName);
            streetList.add(streetName);
        }

        intStreet();
    }

    @Override
    public void setErrorMessage(ErrorMessage error) {
        super.setErrorMessage(error);
        System.out.println("-------错误"+error.getMessage());
    }

    public void intStreet(){

        optionsPickerView = new OptionsPickerBuilder(AuthActivity.this, new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                street = streets.get(options1).id;
                Log.e("333333333333333", streets.get(options1).name);
                edtStreet.setText(streets.get(options1).name);
            }
        })
                .setSelectOptions(0)
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("")//标题
                .setOutSideCancelable(false)
                .build();

        optionsPickerView.setPicker(streetList);

    }

    @Override
    public void setFlowerInfo(FlowerInfoEntity entity) {
        if (entity == null) {
            return;
        }
        flowerInfoEntity = entity;
    }

    @Override
    public void authSuccess(UserModeConfig userModeConfig) {
        dismissCommonSubmitDialog();
        CashOutActivity.actionStart(this, flowerInfoEntity);
        finish();
    }
}
